#! /usr/bin/env python
# -*- coding: utf-8 -*-
#  Auth: IAN
#  Date: 2017/6/22
#  DESC: pdf簽名
# 需要模塊：
#   pyPdf       ： pip install pypdf
#   reportlab   ： pip install reportlab
# 1.
# 2. 新增生成簽名檔的函數
#  ---------------------------
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import uuid
import os
import datetime
from PIL import Image, ImageDraw2,ImageDraw
# from wfs.function.produce_pdf import page_num
import PyPDF2
import reportlab.pdfgen.canvas
import reportlab.lib.units
#  ---------------------------
from django.conf import settings
SIGN_MODE_FIRST = 1  # 只簽首頁
SIGN_MODE_LAST = 2  # 只簽最後一頁
SIGN_MODE_ALL = 4  # 所有頁都簽核
SIGN_MODE_CUSTOMER = 8  # 用戶自定義

UNIT_CM = reportlab.lib.units.cm  # 釐米
UNIT_INCH = reportlab.lib.units.inch  # 英吋
UNIT_MM = reportlab.lib.units.mm  # 毫米
UNIT_PICA = reportlab.lib.units.pica
REMOTE_PATH = settings.MEDIA_ROOT+'pdf/'
# REMOTE_PATH = "D:/photos/files/ST/workflow/file/"
# REMOTE_PATH = 'E:/delpdf/'


def gen_sign_picture(
    sign_picture,
    sign_title,
    sign_time=datetime.datetime.now(),
    sign_font_color="black",
    sign_font_family=REMOTE_PATH+"simfang.ttf",
    sign_title_font_size=12,
    sign_date_font_size=12,
    canvas_size=(132, 44),
    canvas_mode="RGB",
    canvas_color=(255, 255, 255),
    sign_size=(56, 42),
    border=True,
    position_line0=(2, 2),
    position_line1=(65, 5),
    position_line2=(65, 18),
    position_line3=(65, 31),
):
    canvas = Image.new(canvas_mode, canvas_size, canvas_color)
    signer = Image.open(sign_picture)
    w, h = signer.size
    # print(w,h)
    if(w > canvas_size[0]):
        w_rate = w / canvas_size[0]
        w = int(w / w_rate)
        h = int(h / w_rate)
    if h > canvas_size[1]:
        h_rate = h / canvas_size[1]
        w = int(w / h_rate)
        h = int(h / h_rate)

    # print(w, h)
    signer = signer.resize((w, h))
    canvas_draw = ImageDraw2.Draw(canvas)
    if border:
        canvas_draw.line((
            (1, 1),
            (canvas_size[0]-1, 1),
            (canvas_size[0]-1, canvas_size[1]-1),
            (1, canvas_size[1]-1),
            (1, 1)
         ), ImageDraw2.Pen("black", width=1)
        )

    ymd = sign_time.strftime("%Y/%m/%d")
    hms = sign_time.strftime("%H:%M:%S")

    font_title = ImageDraw2.Font(sign_font_color, sign_font_family, sign_title_font_size)
    font_date = ImageDraw2.Font(sign_font_color, sign_font_family, sign_date_font_size)
    canvas_draw.text(position_line1, sign_title, font_title)
    canvas_draw.text(position_line2, ymd, font_date)
    canvas_draw.text(position_line3, hms, font_date)
    canvas.paste(signer, position_line0)
    return canvas


def gen_dummy_sign_picture(
    sign_owner,
    sign_title,
    sign_time=datetime.datetime.now(),
    sign_font_color="black",
    sign_font_family=REMOTE_PATH+"simfang.ttf",
    sign_title_font_size=12,
    sign_date_font_size=12,
    canvas_size=(132, 44),
    canvas_mode="RGB",
    canvas_color=(255, 255, 255),
    sign_size=(56, 42),
    border=True,
    position_line0=(13, 18),
    position_line1=(65, 5),
    position_line2=(65, 18),
    position_line3=(65, 31),

):
    canvas = Image.new(canvas_mode, canvas_size, canvas_color)
    canvas_draw = ImageDraw2.Draw(canvas)
    if border:
        canvas_draw.line((
            (1, 1),
            (canvas_size[0]-1, 1),
            (canvas_size[0]-1, canvas_size[1]-1),
            (1, canvas_size[1]-1),
            (1, 1)
         ), ImageDraw2.Pen(sign_font_color, width=1)
        )

    font_title = ImageDraw2.Font(sign_font_color, sign_font_family, sign_title_font_size)
    font_date = ImageDraw2.Font(sign_font_color, sign_font_family, sign_date_font_size)
    canvas_draw.text(position_line0, sign_owner, font_title)
    canvas_draw.text(position_line1, sign_title, font_title)
    canvas_draw.text(position_line2, u"", font_date)
    canvas_draw.text(position_line3, u"", font_date)
    return canvas


class PdfSign(object):

    def __init__(
            self, path_pdf, path_image, sign_size_width, sign_size_height,
            sign_location_x, sign_location_y,form_size_width,form_size_height,
            form_location_x,form_location_y,form_img,serial_num,
            size_unit=UNIT_MM,
            new_file=None,  # 新的pdf文件名稱
            sign_mode=SIGN_MODE_LAST,  # 只簽最後一頁
            custom_pages=None,
    ):
        """ 構造函數

        :param path_pdf: PDF文件路徑
        :param path_image: 簽名圖片路徑
        :param sign_size_width: 簽名寬度
        :param sign_size_height:  簽名高度
        :param sign_location_x:  簽名頁面位置X坐標(左下開始)
        :param sign_location_y:  簽名頁面位置Y坐標(坐下開始)
        :param size_unit: 長度單位，定位簽名位置和寬高。默認為mm(毫米)
        :param new_file: 新的pdf文件名稱，如果為None，則會隨機生成一個文件名
        :param sign_mode: 簽核模式，默認為只簽最後一頁
        :param custom_pages: 如果指定簽核模式為custom，則需要指定一個list的頁碼信息
        :return:
        """
        self._pdf_path = path_pdf
        self._image_path = path_image
        self._form_img = form_img
        self._sign_width = sign_size_width
        self._sign_height = sign_size_height
        self._location_x = sign_location_x
        self._location_y = sign_location_y
        self._form_width = form_size_width
        self._form_height = form_size_height
        self._form_x = form_location_x
        self._form_y = form_location_y
        self._size_unit = size_unit
        self._ser_num = serial_num
        self._new_file = new_file
        if new_file is None:
            self._new_file = "%s.pdf" % uuid.uuid4().hex
        self._sign_file = REMOTE_PATH+"tmp.pdf.tmp"
        self._time_file = REMOTE_PATH+'tim.pdf.tmp'
        self._form_file = REMOTE_PATH+"tmp.pdf1.tmp"
        self._sign_mode = sign_mode
        self._custom_page = custom_pages
        if custom_pages is None:
            self._custom_page = []
        elif isinstance(custom_pages, (list, tuple)):
            pass
        elif isinstance(custom_pages, str):
            self._custom_page = map(lambda x: int(x), custom_pages.split(','))
        elif isinstance(custom_pages, (int,  float)):
            self._custom_page = [int(custom_pages)]
        else:
            raise TypeError(
                "expect custom_page is list or tuple, received '%s'" %
                custom_pages.__class__.__name__
            )

    @property
    def new_file(self):
        """
        :return: 新文件的名稱
        """
        return self._new_file

    def _create_sign(self):
        """ 創建一個簽名檔
        :return: 簽核當pdf
        """
        canvas = reportlab.pdfgen.canvas.Canvas(
            self._sign_file,
            pagesize=(
                self._sign_width * self._size_unit,
                self._sign_height * self._size_unit
            )
        )
        canvas.drawImage(
            self._image_path,
            self._location_x * self._size_unit,
            self._location_y * self._size_unit,
            width=self._sign_width * self._size_unit,
            height=self._sign_height * self._size_unit
        )

        canvas.setFillAlpha(0.3)
        canvas.save()
        try:
            return PyPDF2.PdfFileReader(open(self._sign_file, "rb"))
        finally:
            pass

    def _create_num(self):
        """ 創建一個簽名檔
        :return: 簽核當pdf
        """
        canvas = reportlab.pdfgen.canvas.Canvas(
            self._form_file,
            pagesize=(
                self._form_width * self._size_unit,
                self._form_height * self._size_unit
            )
        )
        canvas.drawImage(
            self._form_img,
            self._form_x * self._size_unit,
            self._form_y * self._size_unit,
            width=self._form_width * self._size_unit,
            height=self._form_height * self._size_unit
        )

        canvas.setFillAlpha(0.3)
        canvas.save()
        try:
            return PyPDF2.PdfFileReader(open(self._form_file, "rb"))
        finally:
            pass

    def pdf_info(self):
        """獲取pdf文件信息
        :returns pages,[{width:,height,}]
        """
        old_pdf = PyPDF2.PdfFileReader(open(self._pdf_path, "rb"))
        page_info = []
        pages = old_pdf.getNumPages()
        for index in range(pages):
            page = old_pdf.getPage(index)
            info = dict(
                index=index,
                width=page.mediaBox.getWidth(),
                height=page.mediaBox.getHeight(),
            )
            page_info.append(info)
        return pages, page_info

    def do_sign(self):
        """執行簽核
        :return None
        """
        old_pdf = PyPDF2.PdfFileReader(open(self._pdf_path, "rb"))
        old_pages = old_pdf.getNumPages()
        new_pdf = PyPDF2.PdfFileWriter()
        sign_page = self._create_sign().getPage(0)

        for index in range(old_pages):
            page = old_pdf.getPage(index)
            # print(index)
            fopa = str(index+1) + "/" + str(old_pages)
            im = Image.new("RGB", (180, 30), (255, 255, 255))
            dr = ImageDraw.Draw(im)
            font = ImageFont.truetype(REMOTE_PATH+"simfang.ttf", 12)
            dr.text((10, 10), self._ser_num+" 頁碼："+fopa, font=font, fill="#000000")
            im.save(self._form_img)
            form_page = self._create_num().getPage(0)
            # print(self._ser_num+" 頁碼："+fopa)
            # page_num(self._ser_num+" 頁碼："+fopa, self._form_img)
            page.mergePage(form_page)
            if self._sign_mode == SIGN_MODE_ALL:
                page.mergePage(sign_page)
            elif self._sign_mode == SIGN_MODE_FIRST:
                if index == 0:
                    page.mergePage(sign_page)
            elif self._sign_mode == SIGN_MODE_LAST:
                if index == (old_pages-1):
                    page.mergePage(sign_page)
            elif self._sign_mode == SIGN_MODE_CUSTOMER:
                if index in self._custom_page:
                    page.mergePage(sign_page)
            else:
                raise ValueError("unknown sign mode '%s'" % self._sign_mode)
            if not page:
                continue

            new_pdf.addPage(page)
        with open(self._new_file, 'wb') as handler:
            new_pdf.write(handler)
        os.remove(self._form_img)

    # def do_form(self):
    #     """執行簽核
    #     :return None
    #     """
    #     old_pdf = PyPDF2.PdfFileReader(open(self._pdf_path, "rb"))
    #     old_pages = old_pdf.getNumPages()
    #     new_pdf = PyPDF2.PdfFileWriter()
    #     sign_page = self._create_sign().getPage(0)
    #     for index in range(old_pages):
    #         page = old_pdf.getPage(index)
    #         if self._sign_mode == SIGN_MODE_ALL:
    #             page.mergePage(sign_page)
    #         elif self._sign_mode == SIGN_MODE_FIRST:
    #             if index == 0:
    #                 page.mergePage(sign_page)
    #         elif self._sign_mode == SIGN_MODE_LAST:
    #             if index == (old_pages-1):
    #                 page.mergePage(sign_page)
    #         elif self._sign_mode == SIGN_MODE_CUSTOMER:
    #             if index in self._custom_page:
    #                 page.mergePage(sign_page)
    #         else:
    #             raise ValueError("unknown sign mode '%s'" % self._sign_mode)
    #         if not page:
    #             continue
    #         new_pdf.addPage(page)
    #     with open(self._new_file, 'wb') as handler:
    #         new_pdf.write(handler)

    def __del__(self):
        if os.path.exists(self._sign_file):
            try:
                os.remove(self._sign_file)
            except WindowsError:
                pass


# if __name__ == '__main__':
#     width = 29.7  # 21cm
#     height = 0.7  # 1.5cm
#     path = '444.pdf'
#     p = 'aaa.jpg'
#     # r = gen_dummy_sign_picture("謝芷晗","主管簽核")
#     # d = "aaa.jpg"
#     # r.save(d)
#     # g = gen_sign_picture("sign.png", "")
#     # p = "test.jpg"
#     # g.save(p)
#     size_w = 132 / UNIT_CM
#     size_h = 44 / UNIT_CM
#     width -= 1
#     for i in range(5):
#         width -= size_w
#         if width < 0:
#             break
#         _new_file = "pdf%d.pdf" % i
#
#         pdf = PdfSign(
#                 path_pdf=path,
#                 path_image=p,
#                 sign_size_width=size_w,
#                 sign_size_height=size_h,
#                 sign_location_x=width,
#                 sign_location_y=height,
#                 size_unit=UNIT_CM,
#                 new_file=_new_file
#         )
#         # print(pdf.pdf_info())
#         pdf.do_sign()
#         width -= 0.5
#         path = _new_file
    # path = "555.pdf"
    # width = 20  # 21cm
    # height = 0.7  # 1.5cm
    # r = gen_dummy_sign_picture("謝芷晗","主管簽核")
    # d = "aaa.jpg"
    # r.save(d)
    # g = gen_sign_picture("sign.png", "")
    # p = "test.jpg"
    # g.save(p)
    # size_w = 132 / UNIT_CM
    # size_h = 44 / UNIT_CM
    # width -= 1
    # for i in range(9):
    #     width -= size_w
    #     if width < 0:
    #         break
    #     _new_file = "pdf%d.pdf" % i
    #
    #     pdf = PdfSign(
    #             path_pdf=path,
    #             path_image=p,
    #             sign_size_width=size_w,
    #             sign_size_height=size_h,
    #             sign_location_x=width,
    #             sign_location_y=height,
    #             size_unit=UNIT_CM,
    #             new_file=_new_file
    #     )
    #     pdf.do_sign()
    #     width -= 0.03
    #     path = _new_file


from PIL import Image,ImageDraw,ImageFont,ImageFilter
def appimg(username):
    data = Image.new('RGB', (132, 44), (255, 255, 255))
    draw = ImageDraw.Draw(data)
    draw.text((10,10),username,fill=(0,0,0))
    data.save('/mysite/files/ST/workflow/img/'+username+'.png')
    # imgname = data.save('/mysite/files/ST/workflow/img/%s.png'%username)
    # print('C:/Python34/%s.png'%username)
    return '/mysite/files/ST/workflow/img/'+username+'.png'
